import os
import uuid
import shutil
from fastapi import APIRouter, Depends, File, UploadFile, HTTPException, status
from sqlalchemy.orm import Session
from typing import List, Optional

from app.db.database import get_db
from app.core.security import get_current_active_user
from app.core.config import settings

router = APIRouter()


@router.post("/image", response_model=dict)
async def upload_image(
    file: UploadFile = File(...),
    current_user: dict = Depends(get_current_active_user),
):
    """上传图片文件"""
    return await upload_file(file, ["image/jpeg", "image/png", "image/gif", "image/webp"], "images")


@router.post("/video", response_model=dict)
async def upload_video(
    file: UploadFile = File(...),
    current_user: dict = Depends(get_current_active_user),
):
    """上传视频文件"""
    return await upload_file(file, ["video/mp4", "video/mpeg", "video/webm"], "videos")


@router.post("/document", response_model=dict)
async def upload_document(
    file: UploadFile = File(...),
    current_user: dict = Depends(get_current_active_user),
):
    """上传文档文件"""
    return await upload_file(
        file, 
        ["application/pdf", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"],
        "documents"
    )


async def upload_file(file: UploadFile, allowed_content_types: List[str], subfolder: str) -> dict:
    """
    通用文件上传处理
    
    参数:
    - file: 上传的文件
    - allowed_content_types: 允许的内容类型列表
    - subfolder: 存储的子文件夹
    
    返回:
    - 包含文件URL的字典
    """
    # 检查文件内容类型
    if file.content_type not in allowed_content_types:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"文件类型不支持。支持的类型：{', '.join(allowed_content_types)}"
        )
    
    # 确保上传目录存在
    upload_dir = os.path.join(settings.MEDIA_ROOT, subfolder)
    os.makedirs(upload_dir, exist_ok=True)
    
    # 生成唯一文件名
    file_extension = os.path.splitext(file.filename)[1]
    unique_filename = f"{uuid.uuid4()}{file_extension}"
    file_path = os.path.join(upload_dir, unique_filename)
    
    # 保存文件
    try:
        with open(file_path, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"文件上传失败: {str(e)}"
        )
    finally:
        file.file.close()
    
    # 返回文件URL
    file_url = f"{settings.MEDIA_URL}{subfolder}/{unique_filename}"
    return {"url": file_url, "filename": unique_filename} 